package net.itst.schwarzerdaumen;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;

import android.app.ListActivity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;

public class NotificationHandler extends ListActivity {

    private SQLiteDatabase db = null;
    private SchwarzerDaumenDatabase database;
    private Cursor curPlants;
    private PlantsListAdapter adapPlants;
    private ListView lvPlants;
    private Button buttonDone;
    private Integer plant_id;
    private Cursor curWPlan;

    @Override
    public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);

	database = new SchwarzerDaumenDatabase(this);
	db = database.getWritableDatabase();
    }

    @Override
    public void onStart() {
	super.onStart();
	showPlants();
    }

    private void showPlants() {
	TimeZone tzLocal = TimeZone.getDefault();
	Locale lcLocal = Locale.getDefault();
	Calendar dtNow = new GregorianCalendar(tzLocal, lcLocal);

	String[] selection = { new SimpleDateFormat("dd.MM.yyyy").format(dtNow
		.getTime()) };
	curPlants = db.query(TablePlants.TABLE_NAME,
		TablePlants.SQL_GET_STATUS, TablePlants.WNEXT + "=?",
		selection, null, null, TablePlants.ID);
	curPlants.moveToFirst();

	startManagingCursor(curPlants);
	adapPlants = new PlantsListAdapter(this, R.layout.notification_item,
		curPlants, TablePlants.SQL_GET_STATUS, new int[] {
			R.id.plant_name, R.id.plant_icon, R.id.plant_status });
	adapPlants.setButton(R.id.btn_done);
	adapPlants.setButtonLabel(this.getText(R.string._Done));

	lvPlants = getListView();

	setListAdapter(adapPlants);
    }

    public void setNewNext(View v) {
	plant_id = (Integer) v.getTag();

	String[] whereArgs = { plant_id.toString() };
	String whereClause = TablePlants.ID + "=?";

	ContentValues values = new ContentValues();
	values.put(TablePlants.WNEXT, checkNewNext());
	db.update(TablePlants.TABLE_NAME, values, whereClause, whereArgs);
	curPlants.requery();
	if (curPlants.getCount() == 0) {
	    Intent intent = new Intent();
	    setResult(RESULT_OK, intent);
	    finish();
	}
	lvPlants.refreshDrawableState();
    }

    @Override
    public void onResume() {
	super.onResume();
    }

    @Override
    public void onDestroy() {
	super.onDestroy();
	curPlants.close();
	curWPlan.close();
	db.close();
    }

    private String checkNewNext() {
	curWPlan = db.query(TablePlants.TABLE_NAME, TablePlants.SQL_GET_DAYS,
		TablePlants.ID + "=?", new String[] { plant_id.toString() },
		null, null, null);

	curWPlan.moveToFirst();

	String nextWatering = "";

	TimeZone tzLocal = TimeZone.getDefault();
	Locale lcLocal = Locale.getDefault();
	Calendar dtNow = new GregorianCalendar(tzLocal, lcLocal);

	/* We want Monday to be 0 and Sunday to be 6 */
	int today = dtNow.get(GregorianCalendar.DAY_OF_WEEK);
	today -= 2;
	today = (today < 0) ? 6 : today;

	/*
	 * Find all planned days and remap them. Remapping works like this: the
	 * current day (today) gets set to 0, all subsequent days will get
	 * numbered from 1 to 6.
	 */
	int j = 7;
	int remap = 0;
	int newNext = 0;
	int oldNext = 7;
	for (int i = 0; i < 7; i++) {
	    if (curWPlan.getInt(i) == 1 && i != today) {
		remap = i - today;
		newNext = (remap < 0) ? remap + 7 : remap;
		j = (newNext < oldNext) ? i : j;
		oldNext = (newNext < oldNext) ? newNext : oldNext;
	    }
	}

	oldNext = (oldNext == 0) ? 7 : oldNext;

	/* At least one day is planned. */
	if (j < 7) {
	    // oldNext = (oldNext == 0) ? 7 : oldNext;

	    Date date = new Date(dtNow.get(GregorianCalendar.YEAR) - 1900,
		    dtNow.get(GregorianCalendar.MONTH), dtNow
			    .get(GregorianCalendar.DAY_OF_MONTH));
	    dtNow.add(GregorianCalendar.DAY_OF_YEAR, oldNext);
	    date = new Date(dtNow.get(GregorianCalendar.YEAR) - 1900, dtNow
		    .get(GregorianCalendar.MONTH), dtNow
		    .get(GregorianCalendar.DAY_OF_MONTH));
	    nextWatering = new SimpleDateFormat("dd.MM.yyyy").format(date
		    .getTime());
	} else {
	    nextWatering = "";
	}

	return nextWatering;

    }
}